package com.qxzl.util;

import com.qxzl.model.Clients;
import com.qxzl.model.Services;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FunctionUtil {


    /**
     * 删除服务器Ip
     * @param ip
     */
    public static void deleteService(String ip){
        for (int i = 0; i <StaticData.services.size() ; i++) {
            if(StaticData.services.get(i).getIp().endsWith(ip)){
                StaticData.services.remove(i);
            }
        }
    }

    /**
     * 删除客户端
     * @param ip
     */
    public static   void deleteClient(String ip){
        for (int i = 0; i <StaticData.clients.size() ; i++) {
            if(StaticData.clients.get(i).getIp().equals(ip)){
                StaticData.clients.remove(i);
            }
        }
    }


    /**
     * 读取文件
     * @param fileUrl
     * @return
     */
    public static String jsonData(String fileUrl){//filename assets目录下的json文件名
        String  jsonDate=null;
        try {
            InputStreamReader inputStreamReader=new InputStreamReader(new FileInputStream(fileUrl),"UTF-8");
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String line;
            StringBuilder stringBuilder=new StringBuilder();
            while ((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();

            jsonDate=stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonDate;
    }

    /**
     *文件地址读取json转换成Services
     * @param fileUrl
     * @return
     */
    public static List<Services> coveServicesJson(String fileUrl){
            String strjson= jsonData(fileUrl);
            List<Services> list= FAST.parseArray(strjson, Services.class);
            return   list == null? new ArrayList<>():list;
    }



    /**
     *文件地址读取json转换成Clients
     * @param fileUrl 文件地址  xx/xx.json
     * @return
     */
    public static List<Clients> coveClientsJson(String fileUrl){
        String strjson= jsonData(fileUrl);
        List<Clients> list= FAST.parseArray(strjson, Clients.class);

        return  list == null? new ArrayList<>():list;
    }


    /**
     *  写入文件
     * @param pathName 文件地址   xxxx/xx.json
     * @param jsonstr  json字符串
     * @return
     */
    public static boolean writeJson(String pathName,String jsonstr) {

        File file=new File(pathName);
        try {
            if(!file.exists()) {
                file.createNewFile();
            }
            FAST.writeDataToFile(file,jsonstr);
            return  true;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return  false;

    }





}
